<!--
 * @Descripttion: 组织机构管理
 * @version:
 * @Author: 穆宏宇
 * @Date: 2020-09-21 14:23:40
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-11-18 18:43:30
-->
<template>
	<div class="organization">
		<el-row :gutter="10">
			<el-col :span="6">
				<el-card class="box-card box-card-tree" :body-style="{ overflowY: 'auto', height: '93%'}">
					<div slot="header" class="clearfix">
						<i class="el-icon-menu orgIcon"></i>
						<span>组织机构</span>
						<!-- <el-button style="float: right; padding: 3px 0" type="text">操作</el-button> -->
						<!-- <el-input style="margin-top: 10px;" v-model="filterText" placeholder="搜索" clearable></el-input> -->
					</div>
					<!--                      lazy                    :default-expand-all="true"
            :load="loadNode"-->
					<el-tree ref="space" :data="treeData" node-key="id" :check-on-click-node="true"
						:expand-on-click-node="true" :props="defaultProps" :filter-node-method="filterNode"
						 @node-click="changeTree" lazy  :default-expand-all="false"
            :load="loadNode" style="width: 100%; display: inline-block;">
						<span class="custom-tree-node" slot-scope="{ node }">
							<!-- <el-tooltip class="item" effect="dark" :content="node.label" placement="top-start" :default-expand-all="true">
							</el-tooltip> -->
							<span>{{ node.label }}</span>
						</span>
					</el-tree>
				</el-card>
			</el-col>
			<el-col :span="18">
				<el-card class="box-card">
					<div slot="header" class="clearfix">
						<i class="el-icon-menu orgIcon"></i>
						<span>机构管理</span>
						<!-- <el-button style="float: right" type="primary" size="mini" @click="handleOpen('add')"
              >新增</el-button
            > -->
			
							<!-- <el-tooltip content="删除" placement="top" style="margin-left: 20px;">
								<el-button icon="el-icon-delete" size="mini" @click="deleteOrgFn(form)">
								</el-button>
							</el-tooltip>
							<el-tooltip content="添加" placement="top">
								<el-button icon="el-icon-plus" size="mini" @click="handleOpen('add', form)">
								</el-button>
							</el-tooltip>
							<el-tooltip content="绘制审批" placement="top">
								<el-button icon="el-icon-warning-outline" size="mini" @click="goActiviti(form)">
								</el-button>
							</el-tooltip> -->
					</div>
					<el-form :label-position="'right'" :rules="rules" label-width="120px" :model="form" label-suffix=":"
						ref="form">
						<el-row>
							<el-col :span="12">
								<el-form-item label="上级机构" v-if="parentName">
									{{ parentName }}
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="机构名称" prop="name">
									<el-input v-model="form.name" disabled="disabled"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="类型" prop="type">
									  <el-select v-model="form.type" placeholder="请选择类型" clearable @change="changeType($event)" disabled="disabled">
									    <el-option value="1" label="组织"></el-option>
									    <el-option value="2" label="部门"></el-option>
									  </el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="组织类型">
									  <el-select v-model="form.organizationType" placeholder="请选择类型" :disabled="form.type == 2" clearable disabled="disabled">
									    <el-option value="1" label="供货组织"></el-option>
									    <el-option value="2" label="采购组织"></el-option>
									  </el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="电话号码" prop="tel">
									<el-input v-model="form.tel" disabled="disabled"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="单位地址">
									<el-input v-model="form.addr" disabled="disabled"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="组织机构编码">
									<el-input v-model="form.organizationCode" disabled="disabled"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="描述">
									<el-input v-model="form.describe" disabled="disabled"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="项目经理">
									  <el-select v-model="form.organizationType" placeholder="请选择项目经理" clearable>
									    <el-option value="1" label="左哥"></el-option>
									    <el-option value="2" label="深哥"></el-option>
									  </el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-button type="primary" @click="handleSubmit" style="float: right;">保 存</el-button>
						</el-row>
							
						<!-- todo 显示供应商信息 -->
					</el-form>
				</el-card>
			</el-col>
		</el-row>
	</div>
</template>

<script>
	// import treeJson from './tree.json'

	import columns from './columns'
	import {
		getOrgTreeLazy,
		createOrg,
		deleteOrg,
		getOrgTree
	} from '@/api/admin.api'

	import {
		checkPhone
	} from '@/validations/validate'
	import {
		createUuid
	} from '@/util/common'
	export default {
		name: 'organization',
		data() {
			return {
				uuid: '',
				columns,
				// 左侧树
				treeData: [],
				// 右侧树
				treeDataTable: [],
				defaultProps: {
					children: 'children',
					label: 'name',
					isLeaf: 'leaf'
				},
				// 分页数据
				pageData: {
					// 当前分页
					pageNum: 1,
					// 分页条数
					pageSize: 10,
					// 数据总数
					total: 0,
				},
				// 表格选中数据
				tableSelectData: [],
				// 显示弹窗
				dialogVisible: false,
				// 弹窗类型 add 新增 ；edit 查看|编辑
				type: 'add',
				// 弹窗标题
				dialogTitle: '',
				// 弹窗中表单数据
				form: {},
				// 上级父级
				parentName: '',
				rules: {
					name: [{
						required: true,
						trigger: 'blur',
						message: '机构名称不能为空'
					}],
					tel: [{
							required: true,
							trigger: 'blur',
							message: '电话号码不能为空'
						},
						{
							validator: checkPhone,
							trigger: 'blur'
						},
					],
					type: [{
						required: true,
						trigger: 'change',
						message: '机构类型不能为空'
					}],
					// organizationType: [{
					// 	required: true,
					// 	trigger: 'change',
					// 	message: '组织类型不能为空'
					// }]
				},
				filterText: ''
			}
		},
		watch: {
			filterText(val) {
				this.$refs.space.filter(val)
			}
		},
		created() {
			// this.getOrgTreeEvent()
		},
		methods: {
			changeType(e){
				console.log("------"+e);
				if(e == 2){
					this.form.organizationType = '';
				}
			},
			goActiviti(row) {
				if(row.id == undefined){
					// this.$message({
					// 	message: '请选择组织或部门',
					// 	type: 'error',
					// })
					// return;
					row.id = row.parentId;
				}
				localStorage.setItem("type", 0);
				this.$router.push({
					path: "/activiti?type=0&deptId=" + row.id
				})
			},
			// 获取组织树
			getOrgTreeEvent() {
				var that = this;
				getOrgTreeLazy('0').then((res) => {
					that.treeData = res
					that.form = {};
				})
			},
			// 组织机构节点数据
			loadNode(node, resolve) {
				if (node.level === 0) {
					getOrgTreeLazy('0').then((res) => {
						res.forEach(item => {
							// 检查是否有叶子节点
							item['leaf'] = false
						})
						if(res.length>0){
							this.form = res[0];
						}
						return resolve(res)
					})
				} else if (node.data.hasChildren) {
					getOrgTreeLazy(node.data.id).then((res) => {
						res.forEach(item => {
							// 检查是否有叶子节点
							item['leaf'] = !item.hasChildren
						})
						return resolve(res)
					})
				} else {
					return resolve([])
				}


			},
			// 打开弹窗 查详情
			handleOpen(type, row) {
				var that = this;
				// if(row.id == undefined){
				// 	this.$message({
				// 		message: '请选择组织或部门',
				// 		type: 'error',
				// 	})
				// 	return;
				// }
				this.uuid = createUuid()
				this.type = type
				if (type === 'add') {
					if(row.id == undefined){
						return;
					}
					const {
						name,
						id
					} = row
					this.form = {
						parentId: id
					}
					this.parentName = name
				} else {
					this.parentName = ''
					const {
						name,
						tel,
						addr,
						organizationCode,
						sortValue,
						describe,
						parentId,
						id,
						sfxysp,
						settlementMethod
					} = row
					this.form = {
						name,
						tel,
						addr,
						organizationCode,
						sortValue,
						describe,
						id,
						parentId,
						sfxysp,
						settlementMethod
					}
				}

				// this.dialogVisible = true
			},
			// 确定
			handleSubmit() {
				var data = this.form;
				console.log(this.form);
				this.$refs.form.validate((valid) => {
					if (valid) {
						if(this.form.type == 1){
							if(this.form.organizationType == '' || this.form.organizationType == null){
								this.$message({
									message: '请选择组织类型',
									type: 'error',
								})
								return;
							}
						}
						createOrg(this.form, this.uuid).then((res) => {
							var type = 'success';
							var msg = this.type == 'add' ? '添加成功！' : '保存成功'
							if(res == '有流程定义需要删除！' || res == '有未处理的审批流程！'){
								msg = res;
								type = 'error'
							}
							
							this.$alert(msg, '提示', {
								confirmButtonText: '确定',
								type: type,
								callback: (action) => {
									this.dialogVisible = false
									// this.getOrgTreeEvent()
									if(res != '有流程定义需要删除！' || res != '有未处理的审批流程！'){
										// location.reload();
										this.getOrgTreeEvent()
									}
								},
							})
						})
					}
				})
			},
			// 删除组织
			deleteOrgFn(row) {
				if(row.id == undefined){
					// this.$message({
					// 	message: '请选择组织或部门',
					// 	type: 'error',
					// })
					// return;
					row.id = row.parentId;
				}
				this.$confirm('确定删除此组织吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}).then(() => {
					const {
						id
					} = row
					deleteOrg(id).then((res) => {
						this.$message({
							message: '删除成功',
							type: 'success',
						})
						this.getOrgTreeEvent()
					})
				})
			},
			// 关闭弹窗
			handleClose(data) {
				console.log(data)
			},
			//表格最大高度
			tableMaxHeight() {
				return window.innerHeight - 160
			},
			// 左侧树点击
			changeTree(item) {
				this.treeDataTable = [item]
				this.form = item;
				this.type = 'edit';
				this.parentName = '';
			},
			//优化之后的代码 不管有几级都可以适用,不过用了递归
			filterNode(value, data, node) {
				console.log(value, data, node)
				if (!value) {
					return true
				}
				let _array = [] //这里使用数组存储 只是为了存储值。
				this.getReturnNode(node, _array, value)
				let result = false
				_array.forEach(item => {
					result = result || item
				})
				return result
			},
			getReturnNode(node, _array, value) {
				let isPass = node && node.label && node.label.indexOf(value) !== -1
				isPass ? _array.push(isPass) : ''
				if (!isPass && node.level != 1 && node.parent) {
					this.getReturnNode(node.parent, _array, value)
				}
			}
		}
	}
</script>

<style scoped lang='scss'>
	.box-card {
		height: calc(100vh - 120px);
		overflow-y: scroll;
	}

	.el-card__body {
		padding: 20px;
		height: calc(100% - 120px);
		overflow-y: scroll;
	}
	/* ::v-deep .el-table__body-wrapper {
		height: calc(100vh - 490px);
		overflow-y: scroll;
	} */
</style>

